<template>
  <div class="login">
    <input placeholder="用户名" v-model="username"/>
    <input type="password" placeholder="密码" v-model="password"/>
    <button @click="onClick()">提交</button>
    <button @click="protectMethod()">提交</button>
  </div>
</template>

<script>
  import axios from 'axios'
  import qs from 'qs'
  export default {
    name: 'login',
    data() {
      return {
        username: '',
        password: ''
      }
    },
    methods: {
      onClick() {
        if (this.username === '') {
          window.alert('用户名不能为空')
          return
        }
        if (this.password === '') {
          window.alert('密码不能为空')
          return
        }
//      axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        axios.post('http://localhost:9090/login', qs.stringify({
          username: this.username,
          password: this.password
        }))
          .then((response) => {
            console.log(response);
            // 判断是否成功
            // 如果成功，获取到token
            this.result = response.data;
            // 保存token到localStorage
            window.localStorage.setItem('token', response.data)
          })
          .catch((error) => {
            console.log(error);
          });
      },
      protectMethod() {
        // 获取token
        let token = window.localStorage.getItem('token');
        if(token && token !== '') {
          axios.post('http://localhost:9090/protect', {
            header: {
              Authentication: token
            }
          })
            .then((response) => {
              console.log(response);
              this.result = response.data;
            })
            .catch((error) => {
              console.log(error);
            });
        } else {
          // 登录信息不存在，需要重新登录
        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
